import { handleMessage } from '@/utils/globalEvent';
import type { App, DirectiveBinding } from 'vue';

/**
 * 复制指令
 * @directive 按钮节流指令：v-copy
 */
interface IElementWithDebounce extends HTMLElement {
	copyData: string | number;
	handleCopy: () => void;
}

const copyDirective = (app: App) => {
	app.directive('copy', {
		mounted(el: IElementWithDebounce, binding: DirectiveBinding) {
			// 获取传入指令的值，即要复制的文本
			el.copyData = binding.value;

			// 点击事件处理函数，将文本复制到剪贴板
			el.handleCopy = () => {
				navigator.clipboard
					.writeText(String(el.copyData))
					.then(() => {
						handleMessage('文本已成功复制到剪贴板');
					})
					.catch(() => {
						handleMessage('文本复制失败', 'error');
					});
			};

			// 在元素上添加点击事件监听器
			el.addEventListener('click', el.handleCopy);
		},
		updated(el: IElementWithDebounce, binding: DirectiveBinding) {
			el.copyData = binding.value;
		},
		beforeUnmount(el: IElementWithDebounce) {
			// 在指令销毁前移除事件监听器
			el.removeEventListener('click', el.handleCopy);
		},
	});
};

export default copyDirective;
